﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using web.core.ViewModels;
using web.core.Models;
using web.component;
using System.Configuration;
using web.data.entities;

namespace web.core.Controllers
{
    public class admArticleController : baseController
    { 
        #region mot so ham dung chung
        //tao ra link ao 
        public ActionResult getlink(string id)
        {
            string text = id;
            string outStr = Ustring.RemoveIllegalCharacters(id);
            return Json(outStr);
        }

        private ArticleCategoyParamEntities ppnewEntities(global_const.E_ARTICLE_PARAM _key, string _desc)
        {
            var it = new ArticleCategoyParamEntities()
            {
                key = ((int)_key == 0) ? "" : ((int)_key).ToString(),
                desc = _desc
            };
            return it;
        }
        private List<ArticleCategoyParamEntities> ListArticleParam()
        {
            return new List<ArticleCategoyParamEntities>(){
                    ppnewEntities(global_const.E_ARTICLE_PARAM.NORMAL, "---"),
                    ppnewEntities(global_const.E_ARTICLE_PARAM.HOT , "Tin nổi bật"),
                    ppnewEntities(global_const.E_ARTICLE_PARAM.NEW , "Tin mới"),
                    ppnewEntities(global_const.E_ARTICLE_PARAM.USER_FULL , "Tin hữu ích"),
                    ppnewEntities(global_const.E_ARTICLE_PARAM.TOP  , "Tin top"),
                    ppnewEntities(global_const.E_ARTICLE_PARAM.MOST_VIEW, "Tin xem nhiều")
                };
        }
        #endregion

        #region list_article_category
        public ActionResult list_article_category()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_list_article_category(string text_search, int? parent)
        {
            int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            return control_list_article_category(text_search, parent, languageId);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_list_article_category(string text_search, int? parent, int? languageId)
        {
            var list_view = new ViewModels.PageListArticleCategoryViewModels();
            TryUpdateModel(list_view);
            if (list_view.languageId != null)
            {
                languageId = list_view.languageId;
            }
            list_view.page_list_article_category = articleModels.getArticleCategoryBuilder(text_search, parent, languageId);
            list_view.list_category_article_parent = articleModels.getListCategoryArticleDropDownlist(null, languageId);
            list_view.list_language = languageModels.get_list_language();
            return PartialView("../Shared/article/control_list_article_category", list_view);
        }

        public ActionResult updateStatusArticleCategory(string id)
        {
            web.data.entities.article_category cate = new data.entities.article_category();
            cate.category_id = int.Parse(id.Split(',')[0]);
            cate.category_status = byte.Parse(id.Split(',')[1]);
            Models.articleModels.updateStatusArticleCategory(cate);

            string outStr = "" + cate.category_status;
            return Json(outStr);
        }

        #endregion

        #region add_article_category - removed
        //public ActionResult add_article_category()
        //{
        //    bool permission = false;
        //    InitPage(ref permission);
        //    ViewBag.permission = permission;
        //    return View();
        //}

        //[ChildActionOnly]
        //[HttpGet]
        //public ActionResult control_add_article_category(int? id)
        //{
        //    var list_langague = languageModels.get_list_language();
        //    List<web.data.entities.article_category_item> listItems = new List<data.entities.article_category_item>();
        //    foreach (var it in list_langague)
        //    {
        //        var cate_item = new web.data.entities.article_category_item();
        //        cate_item.language_id = it.language_id;
        //        cate_item.category_item_enable = true;

        //        listItems.Add(cate_item);
        //    }

        //    int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
        //    ViewBag.isAdd = true;
        //    var cate_view = new ViewModels.ArticleCategoyViewModels();
        //    cate_view.category_status = 1;
        //    cate_view.listParent = articleModels.getListCategoryArticleDropDownlist(null, languageId);
        //    cate_view.listItems = listItems;
        //    cate_view.listLanguage = list_langague;
        //    if (id != null)
        //    {
        //        cate_view.category_parent = id;
        //    }
        //    return PartialView("../Shared/article/control_article_category", cate_view);
        //}

        //[ChildActionOnly]
        //[HttpPost]
        //public ActionResult control_add_article_category(FormCollection collection)
        //{
        //    var cate_view = new ViewModels.ArticleCategoyViewModels();
        //    TryUpdateModel(cate_view);

        //    if (cate_view.listItems.Count==0 || string.IsNullOrEmpty(cate_view.listItems[0].category_name) || string.IsNullOrEmpty(cate_view.listItems[0].category_alias))
        //    {
        //        ViewBag.result_message = "Vui lòng nhập tên và alias cho danh mục";
        //        ViewBag.isAdd = true;
        //        ViewBag.result = false;
        //        return PartialView("../Shared/article/control_article_category", cate_view);
        //    }
                      
        //    web.data.entities.article_category cate = new data.entities.article_category();
        //    cate.category_status = cate_view.category_status;
        //    cate.category_sort = cate_view.category_sort;
        //    cate.category_parent = cate_view.category_parent;
        //    cate.category_param = cate_view.category_param;

        //    //if category_name is Empty or null ==> remove that item 
        //    for (int i = cate_view.listItems.Count - 1; i >= 0; i--)
        //    {
        //        if (string.IsNullOrEmpty(cate_view.listItems[i].category_name) || string.IsNullOrEmpty(cate_view.listItems[i].category_alias))
        //        {
        //            cate_view.listItems.RemoveAt(i);
        //        }
        //    }

        //    int new_id = articleModels.createArticleCategory(cate,cate_view.listItems);

        //    if (new_id > 0)
        //    {
        //        ViewBag.result_message = "Thêm mới danh mục bài viết thành công.";
        //        ViewBag.result = true;
        //        ViewBag.redirect = "/vi/admArticle/list_article_category";
        //        return PartialView("../Shared/control_redirect");
        //    }
        //    else
        //    {
        //        ViewBag.result_message = "Thêm mới danh mục thất bại.";
        //        ViewBag.isAdd = true;
        //        ViewBag.result = false;
        //        return PartialView("../Shared/article/control_article_category", cate_view);
        //    }
        //}
        #endregion

        #region delete_article_category
        //Xóa artcile category
        public ActionResult delete_article_category()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        public ActionResult control_delete_article_category(int? category_id, string text_search, int? parent, int? languageId)
        {
            if (category_id != null)
            {
                articleModels.deleteArticleCategory(category_id ?? 0);
            }

            ViewBag.result_message = "Xóa danh mục thành công";
            ViewBag.result = true;
            ViewBag.redirect = "/vi/admArticle/list_article_category";
            return PartialView("../Shared/control_redirect");
        }
        #endregion

        #region add/edit_article_category
        public ActionResult edit_article_category()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_edit_article_category(int? id)
        {
            var list_langague = languageModels.get_list_language();
            var listItems = new List<data.entities.article_category_item>();
            var list_Items_old = articleModels.GetListArticleCategoryItemsByCateID(id??0, null);     //get all article category items with all languages
            int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);
            ViewModels.ArticleCategoyViewModels cate_view;
            var lstParam = ListArticleParam();

            if (list_Items_old.Count > 0)
            {
                //edit
                ViewBag.isAdd = false;
                if (list_Items_old.Count < list_langague.Count)
                {
                    for (int i = 0; i < list_langague.Count; i++)
                    {
                        var cate_item = new web.data.entities.article_category_item();
                        cate_item.language_id = list_langague[i].language_id;
                        cate_item.category_item_enable = true;

                        listItems.Add(cate_item);
                    }

                    for (int i = 0; i < list_Items_old.Count; i++)
                    {
                        for (int j = 0; j < listItems.Count; j++)
                        {
                            if (listItems[j].language_id == list_Items_old[i].language_id)
                            {
                                listItems.RemoveAt(j);
                                listItems.Add(list_Items_old[i]);
                            }
                        }
                    }
                }
                else
                {
                    listItems = list_Items_old;
                }

                var art_cate = articleModels.GetArticleCategoryByID(id ?? 0);                   // get article category 
                //int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);

                  cate_view = new ViewModels.ArticleCategoyViewModels()
                {
                    category_status = art_cate.category_status,
                    category_id = art_cate.category_id,
                    category_param = art_cate.category_param,
                    category_parent = art_cate.category_parent,
                    category_sort = art_cate.category_sort,
                    images = art_cate.images,
                    image_display = Ufile.LoadImage(sUrl, art_cate.images),
                    listParent = articleModels.getListCategoryArticleDropDownlist(null, languageId),
                    listItems = listItems,
                    listLanguage = list_langague,
                    select_list_param = new SelectList(lstParam, "key", "desc")
                };
                
            }
            else { 
            //add
                ViewBag.isAdd = true; 
                foreach (var it in list_langague)
                {
                    var cate_item = new web.data.entities.article_category_item();
                    cate_item.language_id = it.language_id;
                    cate_item.category_item_enable = true;

                    listItems.Add(cate_item);
                }
                
                cate_view = new ViewModels.ArticleCategoyViewModels()
                {
                    category_status = 1,
                    listParent = articleModels.getListCategoryArticleDropDownlist(null, languageId),
                    listItems = listItems,
                    listLanguage = list_langague,
                    select_list_param = new SelectList(lstParam, "key", "desc")
                };
               
                var idp = Request.QueryString["idp"];
                if (idp != null)
                {
                    cate_view.category_parent = Convert.ToInt16(idp);
                }
                return PartialView("../Shared/article/control_article_category", cate_view);
            }
            return PartialView("../Shared/article/control_article_category", cate_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_edit_article_category(FormCollection collection)
        {
            var cate_view = new ViewModels.ArticleCategoyViewModels();
            TryUpdateModel(cate_view);

            bool is_edit = false;
            if (cate_view.category_id != 0 && cate_view.category_id != null)
                is_edit = true;

            if (cate_view.listItems.Count==0 || string.IsNullOrEmpty(cate_view.listItems[0].category_name) || string.IsNullOrEmpty(cate_view.listItems[0].category_alias))
            {
                ViewBag.result_message = "Vui lòng nhập tên và alias cho danh mục";
                ViewBag.isAdd = is_edit;
                ViewBag.result = false;
                return PartialView("../Shared/article/control_article_category", cate_view);
            }
            bool isdel = is_edit ? true : false;

            var cate = new data.entities.article_category()
            {
                category_status = cate_view.category_status,
                category_sort = cate_view.category_sort,
                category_parent = cate_view.category_parent,
                category_param = cate_view.category_param,
                category_id = cate_view.category_id ?? 0,
                //images = cate_view.images
                images = SaveImage(isdel, cate_view.images, cate_view.fileUpload, admin_const.E_IMG_TYPE.CATALOG, admin_const.E_IMG_THUMB.NO_THUMB),
            };

            //if category_name is Empty or null ==> remove that item 
            for (int i = cate_view.listItems.Count - 1; i >= 0; i--)
            {
                if (string.IsNullOrEmpty(cate_view.listItems[i].category_name) || string.IsNullOrEmpty(cate_view.listItems[i].category_alias))
                {
                    cate_view.listItems.RemoveAt(i);
                }
            }
            //save db
            if (is_edit)
            {
                articleModels.editArticleCategory(cate, cate_view.listItems);

                ViewBag.result_message = admin_const.UPDATE_OK;
                ViewBag.result = true;
                ViewBag.redirect = "/vi/admArticle/list_article_category";
                return PartialView("../Shared/control_redirect");
            }
            else {
                int new_id = articleModels.createArticleCategory(cate, cate_view.listItems);

                if (new_id > 0)
                {
                    ViewBag.result_message = admin_const.ADD_OK;
                    ViewBag.result = true;
                    ViewBag.redirect = "/vi/admArticle/list_article_category";
                    return PartialView("../Shared/control_redirect");
                }
                else
                {
                    ViewBag.result_message = admin_const.ADD_FAIL;
                    ViewBag.isAdd = true;
                    ViewBag.result = false;
                    return PartialView("../Shared/article/control_article_category", cate_view);
                }
            }
        }
        #endregion

        #region list_article
        public ActionResult list_article()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_list_article(string text_search, int? cateId, string showStyle)
        {
            int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            int currentPage = 1;
            int pageSize = admin_const.PAGE_LIST_SIZE;  //default pagesize = 10
            if (string.IsNullOrEmpty(showStyle))
            {
                showStyle = "grid";                 //default style is grid
            }
            ViewBag.style = showStyle;
            ViewBag.orderBy = "created"; //default order by created date
            ViewBag.orderType = "desc"; //default sort by desc
            return control_list_article(text_search, cateId, languageId, currentPage, pageSize, "created", "desc",showStyle);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_list_article(string text_search, int? cateId, int? languageId, int? page, int? pageSize, string orderBy, string orderType, string showStyle)
        {
            page = Request.QueryString["page"] != null ? int.Parse(Request.QueryString["page"].ToString()) : 1;
            var total = 0;
            List<SelectListItem> sizeDrop = GetSizePagingPublic(pageSize ?? 10);

            List<SelectListItem> orderDrop = new List<SelectListItem>();
            orderDrop.AddRange(new SelectListItem[] { 
                            new SelectListItem{Selected=orderBy=="title"?true:false, Text = "Tiêu đề", Value = "title" },
                            new SelectListItem{Selected=orderBy=="created"?true:false, Text = "Khởi tạo", Value = "created" },
                            new SelectListItem{Selected=orderBy=="modifyed"?true:false, Text = "Cập nhật", Value = "modifyed" },
                            new SelectListItem{Selected=orderBy=="article_status"?true:false, Text = "Trạng thái", Value = "article_status" }
                        }); 

            var list_view = new ViewModels.PageListArticleViewModels();
            TryUpdateModel(list_view);
            if (list_view.languageId != null)
            {
                languageId = list_view.languageId;
            }
            list_view.page_list_article = articleModels.GetListArticleByCategoryID(languageId, cateId, (page??1), (pageSize??10), orderBy, orderType, out total);
            list_view.list_category_article = articleModels.getListCategoryArticleDropDownlist(null, languageId);
            list_view.list_language = languageModels.get_list_language();
            list_view.text_search = text_search;
            list_view.total = total;
            list_view.list_pagesize = sizeDrop;
            list_view.pagesize = pageSize ?? 10;
            list_view.list_order = orderDrop;
            list_view.orderBy = orderBy;
            list_view.orderType = orderType;
            list_view.showStyle = showStyle;
            return PartialView("../Shared/article/control_list_article", list_view);
        }

        public ActionResult updateStatusArticle(string id)
        {
            web.data.entities.article art = new data.entities.article();
            art.article_id = int.Parse(id.Split(',')[0]);
            art.article_status = byte.Parse(id.Split(',')[1]);
            Models.articleModels.updateStatusArticle(art);

            string outStr = "" + art.article_status;
            return Json(outStr);
        }
        #endregion

        #region add_article-- removed
        //public ActionResult add_article()
        //{
        //    bool permission = false;
        //    InitPage(ref permission);
        //    ViewBag.permission = permission;
        //    return View();
        //}

        //[ChildActionOnly]
        //[HttpGet]
        //public ActionResult control_add_article(int? id)
        //{
        //    var list_langague = languageModels.get_list_language();
        //    List<web.data.entities.article_item> listItems = new List<data.entities.article_item>();
        //    foreach (var it in list_langague)
        //    {
        //        var art_item = new web.data.entities.article_item();
        //        art_item.language_id = it.language_id;
        //        art_item.article_item_enable = true;

        //        listItems.Add(art_item);
        //    }
        //    string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);

        //    int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
        //    ViewBag.isAdd = true;
        //    var art_view = new ViewModels.ArticleViewModels();
        //    art_view.article_status = 1;
        //    art_view.listCategory = articleModels.getListCategoryArticleDropDownlist(null, languageId);
        //    art_view.listItems = listItems;
        //    art_view.listLanguage = list_langague;
        //    art_view.image_display = Ufile.LoadImage(sUrl, "");
        //    if (id != null)
        //    {
        //        //id is category_id
        //        art_view.cate_id = id;
        //    }
        //    return PartialView("../Shared/article/control_article", art_view);
        //}

        //[ChildActionOnly]
        //[HttpPost]
        //[ValidateInput(false)]
        //public ActionResult control_add_article(FormCollection collection)
        //{
        //    int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            

        //    var art_view = new ViewModels.ArticleViewModels();
        //    TryUpdateModel(art_view);

        //    if (art_view.listItems.Count == 0 || string.IsNullOrEmpty(art_view.listItems[0].title) || string.IsNullOrEmpty(art_view.listItems[0].alias))
        //    {
        //        var list_langague = languageModels.get_list_language();
        //        List<web.data.entities.article_item> listItems = new List<data.entities.article_item>();
        //        foreach (var it in list_langague)
        //        {
        //            var art_item = new web.data.entities.article_item();
        //            art_item.language_id = it.language_id;
        //            art_item.article_item_enable = true;

        //            listItems.Add(art_item);
        //        }
        //        art_view.listLanguage = list_langague;
        //        art_view.listCategory = articleModels.getListCategoryArticleDropDownlist(null, languageId);
        //        art_view.listItems = listItems;
        //        ViewBag.result_message = "Vui lòng nhập tiêu đề và alias cho bài viết";
        //        ViewBag.isAdd = true;
        //        ViewBag.result = false;
        //        return PartialView("../Shared/article/control_article", art_view);
        //    }
        //    bool isdel = art_view.article_id != 0 ? true : false;
        //    web.data.entities.article art = new data.entities.article();
        //    art.article_status = art_view.article_status;
        //    art.created = Udate_time.GetCurrentDateTime();
        //    art.modifyed = Udate_time.GetCurrentDateTime();
        //    art.created_by = int.Parse(Session["user_id"].ToString());
        //    //art.images = art_view.images;
        //    art.images = SaveImage(isdel, art_view.images, art_view.fileUpload, admin_const.E_IMG_TYPE.ARTICLE, admin_const.E_IMG_THUMB.NO_THUMB);
            

        //    //if category_name is Empty or null ==> remove that item 
        //    for (int i = art_view.listItems.Count - 1; i >= 0; i--)
        //    {
        //        if (string.IsNullOrEmpty(art_view.listItems[i].title) || string.IsNullOrEmpty(art_view.listItems[i].alias))
        //        {
        //            art_view.listItems.RemoveAt(i);
        //        }
        //    }

        //    List<web.data.entities.article_ref_category> list_ref = new List<data.entities.article_ref_category>();
        //    if (!string.IsNullOrEmpty(art_view.arr_article_category) && art_view.arr_article_category.Contains(","))
        //    {                
        //        var arr_cate = art_view.arr_article_category.Split(',');
        //        int[] arr_cate_int = arr_cate.Select(n => Convert.ToInt32(n)).ToArray();
        //        foreach(var it in arr_cate_int)
        //        {
        //            web.data.entities.article_ref_category art_ref = new data.entities.article_ref_category() { 
        //                category_id = it
        //            };
        //            list_ref.Add(art_ref);
        //        }              
        //    }

        //    int new_id = articleModels.createArticle(art, art_view.listItems, list_ref);

        //    if (new_id > 0)
        //    {
        //        ViewBag.result_message = "Thêm mới bài viết thành công.";
        //        ViewBag.result = true;
        //        ViewBag.redirect = "/vi/admArticle/list_article";
        //        return PartialView("../Shared/control_redirect");
        //    }
        //    else
        //    {
        //        var list_langague = languageModels.get_list_language();
        //        List<web.data.entities.article_item> listItems = new List<data.entities.article_item>();
        //        foreach (var it in list_langague)
        //        {
        //            var art_item = new web.data.entities.article_item();
        //            art_item.language_id = it.language_id;
        //            art_item.article_item_enable = true;

        //            listItems.Add(art_item);
        //        }
        //        art_view.listLanguage = list_langague;
        //        art_view.listCategory = articleModels.getListCategoryArticleDropDownlist(null, languageId);
        //        art_view.listItems = listItems;
        //        ViewBag.result_message = "Thêm mới bài viết thất bại.";
        //        ViewBag.isAdd = true;
        //        ViewBag.result = false;
        //        return PartialView("../Shared/article/control_article", art_view);
        //    }
        //}
        #endregion

        #region add/ edit_article
        public ActionResult edit_article()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_edit_article(int? id)
        {
            int itemid = id ?? 0;
            if (itemid == 0)
                ViewBag.isAdd = true;
            else
                ViewBag.isAdd = false;
            var art_view = loadArticleViewModels(id);

            return PartialView("../Shared/article/control_article", art_view);
        }

        public ArticleViewModels loadArticleViewModels(int? id)
        {
            var list_langague = languageModels.get_list_language();
            var listItems = new List<data.entities.article_item>();
            string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);
            int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            ViewModels.ArticleViewModels art_view;

            var art = articleModels.GetArticleByID(id ?? 0);
            if (art != null)
            {
                //--------------edit
                ViewBag.isAdd = false;
                var list_items_old = articleModels.GetListArticleItemsByArticleID(id ?? 0, null);

                listItems = list_items_old;

                //if (list_items_old.Count < list_langague.Count)
                // {
                // kiem tra neu chua ton tai item theo ngon ngu, them moi
                for (int i = 0; i < list_langague.Count; i++)
                {
                    bool is_exist_it = false;
                    for (int j = 0; j < list_items_old.Count; j++)
                    {
                        if (listItems[j].language_id == list_langague[i].language_id)
                            is_exist_it = true;
                    }
                    // them item theo ngon ngu
                    if (is_exist_it == false)
                    {
                        var art_item = new web.data.entities.article_item()
                        {
                            language_id = list_langague[i].language_id,
                            article_item_enable = true
                        };
                        listItems.Add(art_item);
                    }
                }
                listItems = listItems.OrderBy(p => p.language_id).ToList();

                art_view = new ViewModels.ArticleViewModels()
                {
                    article_status = art.article_status,
                    images = art.images,
                    url = art.url,
                    article_id = art.article_id,
                    created = art.created,
                    created_by = art.created_by,
                    listCategory = articleModels.getListCategoryArticleDropDownlist(null, languageId),
                    listItems = listItems,
                    listLanguage = list_langague,
                    image_display = Ufile.LoadImage(sUrl, art.images)
                };

                // danh muc tin
                var list_arr = articleModels.GetListCategoryByArticleID(id ?? 0).ToList();
                for (int i = 0; i < list_arr.Count(); i++)
                {
                    art_view.arr_article_category = art_view.arr_article_category + list_arr[i].ToString() + ",";
                }
                if (art_view.arr_article_category != null)
                {
                    if (art_view.arr_article_category.EndsWith(","))
                    {
                        art_view.arr_article_category = art_view.arr_article_category.Substring(0, art_view.arr_article_category.LastIndexOf(","));
                    }
                }
            }
            else
            {
                //--------------add
                ViewBag.isAdd = true;
                foreach (var it in list_langague)
                {
                    var art_item = new web.data.entities.article_item()
                    {
                        language_id = it.language_id,
                        article_item_enable = true
                    };
                    listItems.Add(art_item);
                }
                art_view = new ViewModels.ArticleViewModels()
                {
                    article_status = 1,
                    listCategory = articleModels.getListCategoryArticleDropDownlist(null, languageId),
                    listItems = listItems,
                    listLanguage = list_langague,
                     image_display = Ufile.LoadImage(sUrl, "")
                };
                //if (id != null)
                //{
                //    //id is category_id
                //    art_view.cate_id = id;
                //}
            }

            return art_view;
        }

        [ChildActionOnly]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult control_edit_article(FormCollection collection)
        {
            var art_view = new ViewModels.ArticleViewModels();
            TryUpdateModel(art_view);
            
            bool is_edit = false;
            if (art_view.article_id != 0 && art_view.article_id != null)
                is_edit = true;

            var count = art_view.listItems.Count;
             //if title is Empty or null ==> remove that item 
           // foreach (var aitem in art_view.listItems)
            for (int i =0; i<count; i++)
            {
                var aitem = art_view.listItems[i];
                if (string.IsNullOrEmpty(aitem.title) || string.IsNullOrEmpty(aitem.alias))
                {
                    if (is_edit)
                        articleModels.deleteArticleItem((int)art_view.article_id, (int)aitem.language_id);
                    art_view.listItems.Remove(aitem);
                }
            }

            if (art_view.listItems.Count <= 0)
            {
                art_view = loadArticleViewModels(art_view.article_id);

                ViewBag.result_message = "Vui lòng nhập tiêu đề và alias cho bài viết";
                //ViewBag.isAdd = false;
                ViewBag.result = false;
                return PartialView("../Shared/article/control_article", art_view);
            }
           
            bool isdel = is_edit ? true : false;
            var art = new data.entities.article()
            {
                article_status = art_view.article_status,
                //images = art_view.images,
                images = SaveImage(isdel, art_view.images, art_view.fileUpload, admin_const.E_IMG_TYPE.ARTICLE, admin_const.E_IMG_THUMB.NO_THUMB),
                url = art_view.url,
                article_id = (int)(art_view.article_id ?? 0),
                modifyed_by = int.Parse(Session["user_id"].ToString()),
                modifyed = Udate_time.GetCurrentDateTime()
            };
            if (!is_edit)
                art.created = Udate_time.GetCurrentDateTime();

            //delete all ref by articleID
            articleModels.DeleteAllArticleRefByArticleID(art_view.article_id ?? 0);

            List<web.data.entities.article_ref_category> list_ref = new List<data.entities.article_ref_category>();
            if (!string.IsNullOrEmpty(art_view.arr_article_category)) //&& art_view.arr_article_category.Contains(","))
            {
                var arr_cate = art_view.arr_article_category.Split(',');
                int[] arr_cate_int = arr_cate.Select(n => Convert.ToInt32(n)).ToArray();
                foreach (var it in arr_cate_int)
                {
                    web.data.entities.article_ref_category art_ref = new data.entities.article_ref_category()
                    {
                        category_id = it
                    };
                    list_ref.Add(art_ref);
                }
            }

            if (is_edit)
            {
                articleModels.editArticle(art, art_view.listItems, list_ref);

                ViewBag.result_message = "Cập nhật bài viết thành công.";
                ViewBag.result = true;
                //ViewBag.redirect = "/vi/admArticle/list_article";
                ViewBag.redirect = "/vi/admArticle/edit_article/" + art.article_id;
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                int new_id = articleModels.createArticle(art, art_view.listItems, list_ref);

                if (new_id > 0)
                {
                    ViewBag.result_message = "Thêm mới bài viết thành công.";
                    ViewBag.result = true;
                    //ViewBag.redirect = "/vi/admArticle/list_article";
                    ViewBag.redirect = "/vi/admArticle/edit_article/" + new_id;
                    return PartialView("../Shared/control_redirect");
                }
                else
                {
                    art_view = loadArticleViewModels(art_view.article_id);
                    ViewBag.result_message = "Thêm mới bài viết thất bại.";
                    ViewBag.isAdd = true;
                    ViewBag.result = false;
                    return PartialView("../Shared/article/control_article", art_view);
                }
            }
        }
        #endregion

        #region delete_article
        //Xóa artcile category
        public ActionResult delete_article()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        public ActionResult control_delete_article(int? article_id)
        {
            if (article_id != null)
            {
                articleModels.deleteArticle(article_id ?? 0);
            }

            ViewBag.result_message = "Xóa bài viết thành công";
            ViewBag.result = true;
            ViewBag.redirect = "/vi/admArticle/list_article";
            return PartialView("../Shared/control_redirect");
        }
        #endregion

        #region  article relate
        public ActionResult article_relate()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        public ActionResult control_article_relate(int? id, string text_search, int? cateId, int? languageId, int? page, int? pageSize)
        {
            var pid = id ?? 0;
            page = Request.QueryString["page"] != null ? int.Parse(Request.QueryString["page"].ToString()) : 1;

            //var total = 0; 
            var page_view = new ViewModels.ArticleRelateViewModels()
            {
                article_id = pid
            };
            TryUpdateModel(page_view);
            if (page_view.languageId != null)
            {
                languageId = page_view.languageId;
            }
            else
                languageId = global_const.LANGUAGE_ID_DEFAULT;

            var save_change = Request.Form["save_change"];
            if (!string.IsNullOrEmpty(save_change))
            {
                int article_id = page_view.article_id;
                //remove from relate
                var lstdelete = Request.Form["is_delete"];
                if (!string.IsNullOrEmpty(lstdelete))
                {
                    var arr = lstdelete.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var iterator in arr)
                    {
                        if (iterator != "false")
                            articleModels.article_relate_delete(article_id, Convert.ToInt16(iterator));
                    }
                }
                //add to relate 
                var lstadd = Request.Form["is_add"];
                if (!string.IsNullOrEmpty(lstadd))
                {
                    var arr = lstadd.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var iterator in arr)
                    {
                        if (iterator != "false")
                        {
                            var pritem = new article_relate()
                            {
                                article_id_a = article_id,
                                article_id_b = Convert.ToInt16(iterator)
                            };
                            if (pritem.article_id_a != pritem.article_id_b) // no ko tu relate den no :)
                                articleModels.article_relate_add(pritem);
                        }
                    }
                }

            }

            var lstCate = articleModels.getListCategoryArticleDropDownlist(null, languageId); 
            var lstLang = languageModels.get_list_language();
            var sizeDrop = GetSizePagingPublic(pageSize ?? admin_const.PAGE_LIST_SIZE);

            page_view.list_relate = articleModels.GetListArticleRelated(pid, -1); // get all
            page_view.list_not_relate = articleModels.GetListArticleNotRelate(pid, text_search, languageId, cateId, (page ?? 1), (pageSize ?? admin_const.PAGE_LIST_SIZE));
            page_view.list_category_article = new SelectList(lstCate, "category_id", "category_name");
            page_view.list_language = new SelectList(lstLang, "language_id", "language_desc");
            page_view.text_search = text_search;
            //  list_view.total = total;
            page_view.list_pagesize = sizeDrop;
            page_view.pagesize = pageSize ?? 10;
            //list_view.list_order = orderDrop;
            //list_view.orderBy = orderBy;
            //list_view.orderType = orderType;
            //list_view.showStyle = showStyle;

            return PartialView("../Shared/article/control_article_relate", page_view);
        }
        #endregion
    }
}
